import { Component, Injector, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute,Params,Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { StaticPageServiceProxy,PagedResultDtoOfStaicPageItem,StaicPageItem,GeneratePagesOut, ConfigFileDto } from '@shared/service-proxies/service-proxies';
import { Paginator } from 'primeng/paginator';
import { Table } from 'primeng/table';
import { AbpSessionService } from 'abp-ng2-module';
import { finalize } from 'rxjs/operators';
import { LazyLoadEvent } from 'primeng/api';
import { map as _map } from 'lodash-es';
import { AppConsts } from '../../../shared/AppConsts';
import { FileUpload } from 'primeng/fileupload';
import { IJsonEditorModalCallbackData, JsonEditorModalComponent } from '@app/shared/common/json-editor/json-editor-modal.component';

@Component({
    templateUrl: './staticPages.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./staticPages.component.less'],
    animations: [appModuleAnimation()]
})
export class StaticPagesComponent extends AppComponentBase {

    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;
    @ViewChild('jsonEditorModal', { static: true }) jsonEditorModal: JsonEditorModalComponent;

    @ViewChild('ExcelFileUpload', { static: false }) excelFileUpload: FileUpload;

    generateResult: GeneratePagesOut = new GeneratePagesOut();
    path: string;
    arr: string[];
    positionDic: string[];
    selectedDatas: string[];
    filterText = '';

    loading = false;

    constructor(
        //private _httpClient: HttpClient,
        injector: Injector,
        private _staticPageServiceProxy: StaticPageServiceProxy,
    ) {
        super(injector);
    }


    ngOnInit() {
        if (abp.session.multiTenancySide === abp.multiTenancy.sides.TENANT) {

            this.path = abp.session2.tenantName + '/' + abp.session2.cultureName;
            //if (!this.feature.isEnabled('App.Device.PcAndMobile')) {
            //    this.path += '/' + 'Pc';
            //}
        }
        this.init();
    }
    ngAfterViewInit(): void {
        this.primengTableHelper.adjustScroll(this.dataTable);
    }

    private init() {
        this.arr = [];
        if (this.path) {
            this.arr = this.path.split("/");
        }
        this.arr.unshift("root");

        this.positionDic = [];
        this.getPath();

        if (abp.session.multiTenancySide === abp.multiTenancy.sides.TENANT) {
            this.arr.shift();
            this.arr.shift();
            this.positionDic.shift();
            this.positionDic.shift();
        }

        this.getGenerateResult();
    }

    private getPath(): void {
        let j, len, i;
        for (j = 0, len = this.arr.length; j < len; j++) {
            let str = "";
            if (j === 0) {
                this.positionDic.push("");
            }
            else {
                for (i = 1, len = this.arr.length; i < len && i <= j; i++) {
                    if (i !== 1) {
                        str += "/";
                        str += this.arr[i];
                    }
                    else {
                        str += this.arr[i];
                    }
                }
                this.positionDic.push(str);
            }
        }
    }

    siteMapBuild(): void {
        //this.message.confirm(this.l('GenerateSiteMapsMessage'), this.l('AreYouSure'),
        //(isConfirmed) => {
        //    if (!isConfirmed) return;
        //     this._staticPageServiceProxy.generateSiteMapTxt()
        //         .subscribe(() => {
        //             this.reloadPage();
        //             this.notify.success(this.l('StaticPageGenerating'));
        //         });
        //})
    }

    visitPageByPath(path: string): void {
        this.message.confirm(this.l('GenerateStaticPageMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._staticPageServiceProxy.visitPage(path)
                    .subscribe(() => {
                        this.reloadPage();
                        this.notify.success(this.l('StaticPageGenerating'));
                    });
            })
    }

    generatePages(path: string): void {
        this.message.confirm(this.l('GenerateStaticPageMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._staticPageServiceProxy.generatePageByPath(path)
                    .subscribe(() => {
                        this.reloadPage();
                        this.notify.success(this.l('StaticPageGenerating'));
                    });
            })
    }

    generateWholeSitePages(): void {
        this.message.confirm(this.l('GenerateStaticPageMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._staticPageServiceProxy.generateWholeSitePages()
                    .subscribe(() => {
                        this.reloadPage();
                        this.notify.success(this.l('StaticPageGenerating'));
                    });
            })
    }

    getGenerateResult(): void {
        this._staticPageServiceProxy.getGeneratePagesResult()
            .subscribe(result => {
                this.generateResult = result;
            });
    }

    getLists(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }
        this.primengTableHelper.showLoadingIndicator();
        this._staticPageServiceProxy.getPageFiles(
            this.path,
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

    getSelectedIds() {
        return _map(this.selectedDatas, selectedMember => selectedMember);
    }

    delete(cpath): void {
        var idList = [];

        if (cpath) {
            idList.push(cpath);
        }
        else {
            idList = this.getSelectedIds();
            idList = idList.map(item => { return item.path; })
        }
        if (idList.length > 0) {
            this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
                (isConfirmed) => {
                    if (!isConfirmed) return;
                    this._staticPageServiceProxy.deleteStaticPages(idList)
                        .subscribe(() => {
                            this.reloadPage();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                })
        }

    }

    reloadPage(): void {
        if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
            return;
        }

        this.getLists(null);
    }

    goToPath(path: string) {
        this.path = path;
        this.init();
        this.getLists();
    }

    config() {
        this.loading = true;
        this._staticPageServiceProxy.getStaticPageConfig()
        .pipe(finalize(() => this.loading = false))
        .subscribe(result => {
            let data: any ={};
            try{
                data = JSON.parse(result);
            }catch(e){
                console.log(e);
            }
            
            this.jsonEditorModal.configure({
                message: 'config',
                data: data,
                schema : this.configSchema
            });
            this.jsonEditorModal.show();
        });
    }
    readonly configSchema: any = {
        'type': 'array',
        'title': '不需要静态页的链接',
        'description':'原始链接中包含以下字符串的都不会生成静态页',
        "uniqueItems": true,
         items:{
            'type': 'string'
         }
        };
      
    configSave(e:IJsonEditorModalCallbackData){
        this.loading = true;
        this._staticPageServiceProxy.createOrUpdateStaticPageConfig(new ConfigFileDto({content: e.data}))
        .pipe(finalize(() => this.loading = false))
        .subscribe(result => {
            this.notify.success(this.l('SavedSuccessfully'));
        });
    }


    // TODO : 待完善
    exportToExcel(): void {
        //let unitId = (this.unitId == 0 ? null : this.unitId);
        //this._userServiceProxy.getUsersToExcel(
        //    this.filterText,
        //    [],
        //    [],
        //    unitId,
        //    this.role !== '' ? parseInt(this.role) : undefined,
        //    this.onlyLockedUsers,
        //    this.primengTableHelper.getSorting(this.dataTable))
        //    .subscribe(result => {
        //        this._fileDownloadService.downloadTempFile(result);
        //    });
    }

    uploadExcel(data: { files: File }): void {
        //const formData: FormData = new FormData();
        //const file = data.files[0];
        //formData.append('file', file, file.name);

        //this._httpClient
        //    .post<any>(this.uploadUrl, formData)
        //    .pipe(finalize(() => this.excelFileUpload.clear()))
        //    .subscribe(response => {
        //        if (response.success) {
        //            this.notify.success(this.l('ImportUsersProcessStart'));
        //        } else if (response.error != null) {
        //            this.notify.error(this.l('ImportUsersUploadFailed'));
        //        }
        //    });
    }

    onUploadExcelError(): void {
        this.notify.error(this.l('ImportUsersUploadFailed'));
    }
}
